package parser

import (
	"fmt"

	"vitess.io/vitess/go/vt/sqlparser"
)

func convertDDL(d sqlparser.DDLStatement, query string) (Statement, error) {
	switch ddl := d.(type) {
	case *sqlparser.AlterTable:
		return convertAlterTable(ddl, query)
	case *sqlparser.DropTable:
		return convertDropTable(ddl, query)
	default:
		return nil, fmt.Errorf("unsupported syntax: %#v", query)
	}
}

func convertAlterTable(n *sqlparser.AlterTable, query string) (Statement, error) {
	stmt := &AlterTableStatement{
		Tbl: n.Table.Name.String(),
	}
	for _, option := range n.AlterOptions {
		switch expr := option.(type) {
		case *sqlparser.AddIndexDefinition:
			if expr.IndexDefinition.Info.Primary {
				stmt.PrimaryKey = expr.IndexDefinition.Columns[0].Column.String()
			}
		default:
			return nil, fmt.Errorf("unsupported syntax: %#v", SQLNodeToString(expr))
		}
	}
	return stmt, nil
}

func convertDropTable(n *sqlparser.DropTable, query string) (Statement, error) {
	stmt := &DropTableStatement{}
	for _, tbl := range n.FromTables {
		stmt.Tbls = append(stmt.Tbls, tbl.Name.String())
	}
	return stmt, nil
}

type AlterTableStatement struct {
	BaseStatement
	Tbl        string
	PrimaryKey string
}

type DropTableStatement struct {
	BaseStatement
	Tbls []string
}
